import { PrismaClient } from '@prisma/client'
import { ValidationArguments, ValidationOptions, registerDecorator } from 'class-validator'

// 验证表字段的唯一性
export function Unique(table: string, fields: string[], validationOptions?: ValidationOptions) {
	return function (object: Record<string, any>, propertyName: string) {
		registerDecorator({
			name: 'Unique',
			target: object.constructor,
			propertyName: propertyName,
			constraints: [table],
			options: validationOptions,
			validator: {
				async validate(value: string, args: ValidationArguments) {
					const prisma = new PrismaClient({ log: ['query'] })
					const res = await prisma[table].findFirst({
						where: {
							OR: fields.map((field) => ({ [field]: value }))
						}
					})
					return !Boolean(res)
				}
			}
		})
	}
}
